package com.zhou.listener;

import cn.hutool.json.JSONUtil;
import com.zhou.domain.Dto.FlightPathDto;
import com.zhou.domain.FlightPath;
import com.zhou.service.impL.FlightPathServiceImpl;
import com.zhou.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisAddFlightPatheListener implements MessageListener {
 
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FlightPathServiceImpl flightPathService;

 
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取消息
        byte[] messageBody = message.getBody();
        // 使用值序列化器转换
        Object msg = redisTemplate.getStringSerializer().deserialize(messageBody);
        // 获取监听的频道
        byte[] channelByte = message.getChannel();
        // 使用字符串序列化器转换
        Object channel = redisTemplate.getStringSerializer().deserialize(channelByte);
        // 渠道名称转换
        String patternStr = new String(pattern);
        System.out.println(patternStr);
        System.out.println("---频道---: " + channel);
        System.out.println("---消息内容---: " + msg);

        try {
            FlightPathDto deserialize = JsonUtil.deserialize((String) msg, FlightPathDto.class);
            FlightPath flightPath = new FlightPath(
                    deserialize.getId(),
                    deserialize.getIcao_code(),
                    deserialize.getTimestamp(),
                    deserialize.getLatitude(),
                    deserialize.getLongitude(),
                    deserialize.getAltitude().intValue(),
                    deserialize.getSpeed().shortValue(),
                    deserialize.getHeading().shortValue(),
                    deserialize.getSource_type()
                    );
            System.out.println(flightPath);

            flightPathService.add(flightPath);
            System.out.println("添加成功");

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}